import PizZip from 'pizzip'
import PizZipUtils from 'pizzip/utils'
import Docxtemplater from 'docxtemplater'
import { saveAs } from 'file-saver'
import { modal } from 'vxe-table'
import ImageModule from 'docxtemplater-image-module-free'

/**
 * 注入数据
 * @param blob 模板数据
 * @param wordData 格式化后word需要的数据
 */
export function readerWordData(blob: Blob, wordData: TypedAny) {
  const reader = new FileReader()
  reader.readAsArrayBuffer(blob)
  reader.onload = ({ target }) => {
    const zip = new PizZip(target?.result || '')
    const imageOptions = {
      getImage(tagValue: string) {
        return new Promise(function (resolve, reject) {
          PizZipUtils.getBinaryContent(tagValue, function (error, content) {
            if (error) {
              return reject(error)
            }
            return resolve(content)
          })
        })
      },
      getSize(img: any, tagValue: string, tagName: string) {
        return new Promise(function (resolve, reject) {
          const image = new Image()
          image.src = tagValue
          image.onload = function () {
            resolve([image.width, image.height])
          }
          image.onerror = function (e) {
            console.log('img, tagValue, tagName : ', img, tagValue, tagName)
            alert('An error occured while loading ' + tagValue)
            reject(e)
          }
        })
      }
    }
    const doc = new Docxtemplater(zip, {
      paragraphLoop: true,
      linebreaks: true,
      modules: [new ImageModule(imageOptions)]
    })

    return doc.renderAsync(wordData).then(() => {
      const buf = doc.getZip().generate({
        type: 'blob',
        mimeType: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
      })
      const fileName = `${wordData.fileName}.docx`
      saveAs(buf, fileName)
      modal.message({ content: `导出 ${fileName} 成功！`, status: 'success' })
      console.log(wordData)
    })
  }
}
